#!/usr/bin/env python
#-*- coding:utf-8 -*-
import ConfigParser
import httplib
import urllib
import threading
import time
import commands
import json
import logging
import traceback
import socket
import os, sys
import MySQLdb
#import pickle


def bmc_ctrl_load_cfg(first_time=True):
	'''
	try:
		cfgfile='/etc/cetusfs/mds.cfg'
		conf = ConfigParser.ConfigParser()
		conf.read(cfgfile)
		BMC_POWEROFF_TIMEOUT = conf.getint("MDS","raid_timeout")*60
		BMC_CTRL_PORT = 8686
		if(first_time):
			BMC_LOGGER = logging.getLogger(__name__)
			BMC_LOGGER.setLevel(conf.getint("BMC","log_level"))
			fh = logging.FileHandler(conf.get("BMC","log_file"),'a')
			fh.setFormatter(logging.Formatter("%(asctime)s - [line:%(lineno)d] - %(levelname)s: %(message)s"))
			BMC_LOGGER.addHandler(fh)
			BMC_IPSDRV_CFG = []
			try:
				f = open('/etc/cetusfs/bmc_ipsdrv.cfg','r')
				raid_cfg_data=f.read()
				BMC_IPSDRV_CFG = json.loads(raid_cfg_data)
				f.close()
				BMC_LOGGER.debug("bmc_ctrl_load_cfg:Finish to load bmc_ipsdrv configs.")
			except:
				BMC_LOGGER.info("bmc_ctrl_load_cfg:Cannot read file [/etc/cetusfs/bmc_ipsdrv.cfg]")
		else:
			BMC_LOGGER.setLevel(conf.getint("BMC","log_level"))
			return
	'''

	return 0

def process_one_msg(connectiontoclient, address):
	print("process_one_msg():Start new thread accept " + str(address))
	req= ''
	req+= connectiontoclient.recv(2048)
	response = {"code":0, "des":""}

	request = json.loads(req)
	r=''
	#request = {"cmd":"command","raid-name":"/raid0_1/path1/path2/111.ts"}
	#print recv_json_msg

	if request['cmd'] == "test":
		response['code'] = 0 
		r = json.dumps(response)
	else:
		response['code'] = -1;
		response['des'] = 'Unknown command.'
	connectiontoclient.send(r)
	connectiontoclient.close()
	#end = time.time()

#BMC 控制器服务端主程序
def BMC_run_server():
	serversocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
	serversocket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
	serversocket.bind(("0.0.0.0", 6080))
	serversocket.listen(1)

	while True:
		try:
			connectiontoclient, address = serversocket.accept()
			threading.Thread(target=process_one_msg,args=(connectiontoclient,address)).start()
		finally:
			serversocket.close()



#Client 函数，向HTTP BCM  CTRL服务器发送消息
def http_send_json_msg(msg):
	# create socket
	s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
	s.connect(("0.0.0.0", 6080))
	s.send(msg)
	data = s.recv(2048)
	decoded = json.loads(data)
	s.close()
	return decoded['code']


#HTTP BCM  CTRL服务器函数

#开启daemon模式，提供http  server服务
def daemon_init(stdin='/dev/null',stdout='/dev/null',stderr='/dev/null'):
	try:
		pid = os.fork()
		if(pid > 0):
			sys.exit(0)
	#except OSError , e:
	except:
		info=sys.exc_info()
		sys.exit(1)

	os.chdir("/")
	os.umask(0)
	os.setsid()

	try:
		pid = os.fork()
		if(pid > 0):
			sys.exit(0)
	except :
		info=sys.exc_info()
		sys.exit(1)
		#sys.stderr.write("fork #1 failed: (%d) %s\n" % (e.errno, e.strerror) ) ;

	for f in sys.stdout, sys.stderr: f.flush()
	si = open(stdin, 'r')
	so = open(stdout, 'a+')
	se = open(stderr, 'a+', 0)
	os.dup2(si.fileno(), sys.stdin.fileno())    #dup2函数原子化关闭和复制文件描述符
	os.dup2(so.fileno(), sys.stdout.fileno())
	os.dup2(se.fileno(), sys.stderr.fileno())

def bmc_find_ctrl_pid():
	cmd='ps -ef | grep server.py'
	status, output = commands.getstatusoutput(cmd)
	output.expandtabs()
	find_daemon_pid = ''
	find_daemon_ppid = ''
	find_daemon_flag = 0
	for lint_t in output.split('\n'):
		if(lint_t.find('python') > 0 and (lint_t.find('start')>0  or lint_t.find('restart')>0)):
			for data_t in lint_t.split(' '):
				if(find_daemon_flag == 1 and data_t != ''):
					find_daemon_pid = data_t
					find_daemon_flag = 2
				elif(find_daemon_flag == 0 ):
					find_daemon_flag = 1
				elif(find_daemon_flag == 2 and data_t != ''):
					find_daemon_ppid = data_t
					find_daemon_flag = 0
					return find_daemon_pid,find_daemon_ppid
	return '',''


def bmc_service_do(do_flag):
	pid,ppid=bmc_find_ctrl_pid()
	if(do_flag == 1):
		if(ppid == '1'):
			print("server allready started ...")
			pass
		else:
			print("server start ...")
			daemon_init()
			BMC_run_server()
	elif(do_flag == 2 and ppid == '1'):
		cmd='kill '+pid
		status, output = commands.getstatusoutput(cmd)
		print("server end ...")
	else:
		print("server service_do unknown ...")

#工具使用说明
def usage():
	print "usage:"

	#服务端软件：以守护进程方式工作，执行客户端命令，同时开启自动下电定时器
	print "    ",sys.argv[0]," start		:服务器 开启HTTP后台服务程序，同时开启下电定时器"
	#print "    ",sys.argv[0]," restart		:服务器 重新开启HTTP后台服务程序，同时开启下电定时器"
	print "    ",sys.argv[0]," stop		:服务器 关闭HTTP后台服务程序，同时关闭下电定时器"
	print "\n"


#主入口函数
if __name__ == '__main__':
	ret = 0
	time_now = time.time()
	bmc_ctrl_load_cfg()
	print("RUN COMMAND::::"+str(sys.argv))
	if(len(sys.argv) < 2):
		usage()
	elif (sys.argv[1] == "start"):
		bmc_service_do(1)
	elif (sys.argv[1] == "stop"):
		bmc_service_do(2)
	elif (sys.argv[1] == "test"):
		request = {"cmd":"test"}
		ret = http_send_json_msg(json.dumps(request))
		print("cmd test, result[%d]",ret)
	else:
		usage()

	print("\nrun end,duration="+str(time.time()-time_now)+" seconds.")
	exit(ret)
